﻿using System;
using System.Threading;

namespace 加锁
{
    internal class Program
    {

        public static int total = 10_000;
        public static int sum = 0;

        // 这是一个锁
        static object lockobj = new object();

        static void Main(string[] args)
        {
            
            Thread thread1 = new Thread(ThreadMethod);
            Thread thread2 = new Thread(ThreadMethod);

            thread1.Start();
            thread2.Start();


            // 等待线程执行完成
            thread1.Join();
            thread2.Join();

            // 然后再执行主线程的代码
            Console.WriteLine($"总和预计是20000，实际是{sum}"); // 总和预计是20000，实际是12957

        }

        static void ThreadMethod()
        {
            for (int i = 0; i < total; i++)
            {
                // 加锁，只能一个线程进入，执行完了，释放锁。另一个线程才能进入
                lock (lockobj)
                {
                    sum += 1;
                }

                //Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:{sum}");
            }
        }
    }
}
